<template>
  <div>
    <h3>{{ time }}</h3>
    <input type="number" v-model.number="count" />

    <button @click="stopWatchCount">停止对count监听</button>
  </div>
</template>

<script>
import { ref, watch, watchEffect } from 'vue'

export default {
  setup() {
    const count = ref(200)
    const time = ref(0)

    // watch返回值是一个函数，执行此函数可以停止对变量的监听
    const stopCountHandle = watch(count, (value) => {
      // console.log('watch', value)
    })
    const stopWatchCount = () => {
      stopCountHandle()
    }

    // onCleanup 清理副作用
    const watchStopHandle = watchEffect((onCleanup) => {
      count.value
      let timer
      onCleanup(() => {
        timer && clearTimeout(timer)
        console.log('清理之前的工作')
      })
      timer = setTimeout(() => {
        time.value = Date.now()
        console.log('watchEffect', count.value)
      }, 1000)
    })

    return {
      count,
      time,
      stopWatchCount
    }
  }
}
</script>

<style lang="scss" scoped></style>
